<template>
  <div class="upload-container">
    <el-button :style="{background:color,borderColor:color}" icon="el-icon-upload" size="mini" type="primary"
      @click=" dialogVisible=true">
      上传图片
    </el-button>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <el-upload :multiple="true" :file-list="fileList" :show-file-list="true" :on-remove="handleRemove"
           :before-upload="beforeUpload" class="editor-slide-upload" action="fakeaction"
        :http-request="uploadSectionFile" list-type="picture-card">
        <el-button size="small" type="primary">
          点击上传
        </el-button>
      </el-upload>
      <el-button @click="dialogVisible = false">
        取消
      </el-button>
      <el-button type="primary" @click="handleSubmit">
        确认
      </el-button>
    </el-dialog>
  </div>
</template>

<script>
  // import { getToken } from 'api/qiniu'
  import getGlobalParams from "@/utils/getGlobalParams";
  import materialUploadNotice from "@/message/knowLedge-manage/Material-manage/MaterialUploadNotice"
  import request from "@/utils/requestKnowledge";

  export default {
    name: 'EditorSlideUpload',
    props: {
      color: {
        type: String,
        default: '#1890ff'
      }
    },
    data() {
      return {
        fileUid:'',
        uploadfile:'',
        dialogVisible: false,
        listObj: {},
        fileList: [],
        fileUrl: getGlobalParams.get("KnowledgeImgUploadAddress"),
        // 素材类型
        imageType: getGlobalParams.get("imageType"),
      }
    },
    methods: {
      checkAllSuccess() {
        return Object.keys(this.listObj).every(item => this.listObj[item].hasSuccess)
      },
      handleSubmit() {
        const arr = Object.keys(this.listObj).map(v => this.listObj[v])
        console.log(this.checkAllSuccess())
        if (!this.checkAllSuccess()) {
          this.$message('请保证上传类型为图片并且都已成功上传！')
          return
        }
        this.$emit('successCBK', arr)
        this.listObj = {}
        this.fileList = []
        this.dialogVisible = false
      },
      // 素材上传通知
      async notice(type, name, path) {
        let resBody = new materialUploadNotice()
        resBody.data.MatType = type
        resBody.data.FileName = name
        // resBody.data.FilePath = getGlobalParams.get("imagePath")
        resBody.data.FilePath = path
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.$message({
            type: 'success',
            // message: '通知成功!'
            message: '上传成功!'
          });
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          });
        }
      },
      // 自定义上传
      uploadSectionFile(params) {
        console.log(params)
        let file = params.file
        this.fileUid = file.uid
        // 根据后台需求数据格式
        this.uploadfile = new File([file], new Date().getTime() + file.name, {
          type: file.type
        })
        const form = new FormData();
        // 文件对象
        form.append("file", this.uploadfile);
        // XMLHttpRequest 对象
        var xhr = new XMLHttpRequest();
        xhr.open("post", this.fileUrl, true); //发送post请求
        xhr.onload = this.uploadComplete; //请求完成
        xhr.onerror = this.uploadFailed; //请求失败
        // xhr.upload.onprogress = this.progressFunction; //【上传进度调用方法实现】
        xhr.send(form);
      },
      // progressFunction(evt) {
      // },
      uploadComplete(evt) {
        //服务断接收完文件返回的结果
        // 图片上传成功发送通知
        this.notice(this.imageType, this.uploadfile.name, getGlobalParams.get("imagePath"))
        const uid = this.fileUid
        const objKeyArr = Object.keys(this.listObj)
        // console.log(this.listObj)
        for (let i = 0, len = objKeyArr.length; i < len; i++) {
          if (this.listObj[objKeyArr[i]].uid === uid) {
            this.listObj[objKeyArr[i]].url = getGlobalParams.get("KnowledgeImgDownloadAddress") + '/' + this.uploadfile.name;
            this.listObj[objKeyArr[i]].hasSuccess = true
            return
          }
        }
      },
      // 上传失败
      uploadFailed(evt) {
        this.$message.warning(`上传失败！`)
      },
      // async handleSuccess(res, file) {
      //   //  图片上传通知
      //   this.notice(this.imageType, file.name, getGlobalParams.get("imagePath"))
      //   const uid = file.uid
      //   const objKeyArr = Object.keys(this.listObj)
      //   for (let i = 0, len = objKeyArr.length; i < len; i++) {
      //     if (this.listObj[objKeyArr[i]].uid === uid) {
      //       this.listObj[objKeyArr[i]].url = getGlobalParams.get("KnowledgeImgDownloadAddress") + '/' + file.name;
      //       this.listObj[objKeyArr[i]].hasSuccess = true
      //       return
      //     }
      //   }
      // },
      handleRemove(file) {
        const uid = file.uid
        const objKeyArr = Object.keys(this.listObj)
        for (let i = 0, len = objKeyArr.length; i < len; i++) {
          if (this.listObj[objKeyArr[i]].uid === uid) {
            delete this.listObj[objKeyArr[i]]
            return
          }
        }
        console.log("objKeyArr", objKeyArr);
      },
      beforeUpload(file) {
        console.log('before')
        if (!(file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpg' || file.type ===
            'image/jpeg')) {
          this.$notify.warning({
            title: '警告',
            message: '请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片'
          })
          return false
        }
        const _self = this
        const _URL = window.URL || window.webkitURL
        const fileName = file.uid
        this.listObj[fileName] = {}
        return new Promise((resolve, reject) => {
          const img = new Image()
          img.src = _URL.createObjectURL(file)
          img.onload = function () {
            _self.listObj[fileName] = {
              hasSuccess: false,
              uid: file.uid,
              width: this.width,
              height: this.height
            }
          }
          resolve(true)
        })
      }
    }
  }

</script>

<style scoped>
  .editor-slide-upload {
    margin-bottom: 20px;
    /* /deep/ .el-upload--picture-card {
    width: 100%;
  } */
  }

</style>
